package com.hwpt.hwaccount.feature.home;

import android.content.Context;

import com.hwpt.hwaccount.core.data.UserTableObserver;
import com.hwpt.hwaccount.core.data.repository.UserInfoRepository;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.schedulers.Schedulers;

public class HomeModel implements HomeContract.Model {
    private final UserInfoRepository repository;
    private final Context context;

    public HomeModel(Context context) {
        this.context = context.getApplicationContext();
        this.repository = new UserInfoRepository(context);
    }

    @Override
    public void loadUserInfo(HomeContract.Model.LoadUserCallback callback) {
        repository.getAllUsers()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(users -> {
                if (users != null && !users.isEmpty()) {
                    callback.onSuccess(users.get(0));
                } else {
                    callback.onError("未找到用户数据");
                }
            }, throwable -> {
                callback.onError("加载用户信息失败: " + throwable.getMessage());
            });
    }

    @Override
    public void logout(HomeContract.Model.LogoutCallback callback, Context context) {
        // 先停止用户表监听
        UserTableObserver observer = UserTableObserver.getInstance(context);
        if (observer.isObserving()) {
            observer.stopObserving();
        }

        // 然后执行原有的退出登录逻辑
        repository.setLoggedIn(false)
                .andThen(repository.clearUserTable())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(() -> {
                    callback.onSuccess();
                }, throwable -> {
                    callback.onError("退出登录失败: " + throwable.getMessage());
                });
    }
}